﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace _5E.Utils.StringHelper.Extension
{
    /// <summary>
    /// 程序说明：字符扩展类
    /// 创建作者：ahl
    /// 创建时间：2012-03-25
    /// </summary>
    public static class StringExtension
    {
        #region 变量

        /// <summary>
        /// 清除特殊符号正则
        /// </summary>
        static Regex cleanRegEx = new Regex(@"\s+|_|-|\.", RegexOptions.Compiled);

        #endregion

        #region Md5

        /// <summary>
        /// 获取Md5加密后的字符串
        /// </summary>
        /// <param name="str">需要转换的Str</param>
        /// <returns></returns>
        public static string GetMd5(this string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encodingBytes = Encoding.Default.GetBytes(str), md5Bytes = md5.ComputeHash(encodingBytes);
            return BitConverter.ToString(md5Bytes);
        }

        /// <summary>
        /// 转化为BCrypt
        /// </summary>
        /// <param name="str">需要转换的字符串</param>
        /// <returns></returns>
        public static string GetBCrypt(this string str)
        {
            return BCrypt.HashPassword(str, BCrypt.GenerateSalt());
        }

        #endregion

        #region Change

        /// <summary>
        /// PascalCase
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string ToPascalCase(this string str)
        {
            string[] names = cleanRegEx.Split(str);
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < names.Length; i++)
            {
                if (string.IsNullOrEmpty(names[i]))
                {
                    result.Append(i == 0 ? "_" : string.Empty);
                    continue;
                }
                result.Append(char.ToUpper(names[i].ToLower()[0]) + names[i].Substring(1));
            }
            return result.ToString();
        }

        #endregion
    }
}
